import {
  GetModelList,
  PostModel,
  DeleteModel, AddModel
} from "@/api/videoLib";
import { getSignature } from '@/api/upload'
import SVideo from '@/components/video/index'
import { GetSelectDicByCode } from '@/api/dictionary'
import { deepClone } from "@/utils"
import TcVod from 'vod-js-sdk-v6'

const defaultModel = {
  Id: "",
  Name: "",
  Description: "",
  CoverUrl: "",
  ShowCoverUrl: "",
  CategoryId: "",
  TypeCode: "",
  Sort: "",
  FileId: "",
  DownloadUrl: "",
  Size: 0
};
export default {
  components: { SVideo },
  data() {

    /**获取腾讯云上传视频签名 */
    function getSignature() {
      return getSignature().then(function (response) {
        console.log('response', response)
        return response.data.Signature
      })
    }

    return {
      viewModel: {
        PageIndex: 1,
        pageSize: 10,
        VideoName: '',
        CategoryId: '',
        TypeCode: ''
      },
      total: 0,
      dialogVisible: false,
      dialogVideoVisible: false,
      dialogType: "",
      model: Object.assign({}, defaultModel),
      modelList: [],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: "",
      playUrl: '',
      loading: false,
      AppCodeList: [
        { key: "", title: "全部" },
        { key: "Android", title: "Android" },
        { key: "IOS", title: "IOS" }
      ],
      rules: {
        Name: [
          { required: true, message: "请输入视频名称", trigger: "blur" },
        ],
        CategoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
        // ShowCoverUrl: [{ required: true, message: "请上传封面", trigger: "blur" }],
        TypeCode: [
          { required: true, message: "请选择基础分类", trigger: "blur" }
        ]
      },
      categoryList: [],
      queryCategoryList: [],
      typeList: [],
      queryTypeList: [],
      tcVod: '',
      uploading: false,
      progressStr: '',
      uploader: '',
      uploaderInfos: [],
      addVisible: false,
      addmodel: {}
    };
  },
  computed: {
    // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
  },
  created() {
    // 实例创建完成后执行的代码
    this.GetModelList(this.viewModel);
    this.actionUrl = this.apiPre + "/Upload/UploadAttachment";
    this.GetDictionaryByPCode()
    this.setTypeList()
    this.init() //初始化腾讯云
  },
  methods: {
    async GetDictionaryByPCode() {
      var res = await GetSelectDicByCode('YTJY');
      if (res && res.code == 200) {
        this.categoryList = res.data.Items
        this.queryCategoryList = deepClone(this.categoryList)
        this.queryCategoryList.unshift({
          id: '',
          value: '',
          label: '全部分类'
        })
      }
    },
    async setTypeList() {
      var res = await GetSelectDicByCode('banji');
      if (res && res.code == 200) {
        this.typeList = res.data.Items
        this.queryTypeList = deepClone(this.typeList)
        this.queryTypeList.unshift({
          value: '',
          label: '全部班级类型'
        })
      }
    },
    async GetModelList(viewModel) {
      this.loading = true
      const res = await GetModelList(viewModel);
      if (res.data) {
        this.total = res.data.TotalCount;
        this.modelList = res.data.Items;
      }

      this.loading = false
    },
    closeDialog() {
      this.uploading = false
      this.progressStr = ''
      this.uploader.cancel()
    },
    closeAddDialog() {
      this.uploaderInfos.forEach(element => {
        element.cancel()
      });
    },
    cancelAdd() {
      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)
      if (t && t.length > 0) {
        this.$confirm('关闭后视频也取消上传，确认关闭？')
          .then(_ => {
            this.addVisible = false
          })
          .catch(_ => { });
      } else {
        this.addVisible = false
      }
    },
    handleClose(done) {
      if (this.uploading) {
        this.$confirm('关闭后视频也取消上传，确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => { });
      } else
        done();
    },
    handleCloseAdd(done) {
      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)
      if (t && t.length > 0) {
        this.$confirm('关闭后视频也取消上传，确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => { });
      } else
        done();
    },
    //视频上传
    uploadVideoForAdd(file) {
      var mediaFile = file
      var uploader = this.tcVod.upload({
        mediaFile: mediaFile, // 媒体文件（视频或音频或图片），类型为 File
      })

      var uploaderInfo = {
        videoInfo: uploader.videoInfo,
        isVideoUploadSuccess: false,
        isVideoUploadCancel: false,
        progress: '0%',
        FileId: '',
        DownloadUrl: '',
        Size: uploader.videoInfo.size,
        Name: uploader.videoInfo.name,
        cancel: function () {
          uploaderInfo.isVideoUploadCancel = true;
          uploader.cancel()
        },
      }

      uploader.on('media_progress', function (info) {
        console.log('info.percent', info.percent, "uploaderInfo--", uploaderInfo) // 进度
        var p = info.percent * 100
        uploaderInfo.progress = p.toFixed(0) + '%'
      })

      uploader.done().then(function (doneResult) {
        // deal with doneResult
        console.log('doneResult', doneResult)
        uploaderInfo.FileId = doneResult.fileId;
        uploaderInfo.DownloadUrl = doneResult.video.url
        uploaderInfo.isVideoUploadSuccess = true

      }).catch(function (err) {
        // deal with error
        console.log('uploader err', err)
      })

      this.uploaderInfos.push(uploaderInfo)
    },
    beforeUploadForAdd(file) {
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]

      const isImg = ext === 'mp4' || ext === 'MP4'

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传文件只能是 MP4 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }

      // this.model.Size = parseInt(file.size / 1024)

      this.uploadVideoForAdd(file);

      return false
    },
    async confirmAddModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["addmodel"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }

      var t = this.uploaderInfos.filter(x => !x.isVideoUploadSuccess)

      if (t && t.length > 0) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "视频上传中，等待视频上传完成后再保存"
        });
        return false;
      }
      this.uploaderInfos.forEach(element => {
        this.addmodel.Items.push(
          {
            FileId: element.FileId,
            DownloadUrl: element.DownloadUrl,
            Size: element.Size / 1024,
            Name: element.Name,
          }
        )
      });
      var res = await AddModel(this.addmodel);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.viewModel.page = 1;
      this.GetModelList(this.viewModel);
      this.model = deepClone(defaultModel);
      this.addVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    queryList() {
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    refresh() {
      this.viewModel.VideoName = ''
      this.viewModel.CategoryId = ''
      this.viewModel.TypeCode = ''
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    lastPage(val) {
      this.viewModel.page = val;
    },
    nextPage(val) {
      this.viewModel.page = val;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.viewModel.pageSize = val;
      this.GetModelList(this.viewModel);
    },
    handleCurrentChange(val) {
      this.viewModel.page = val;
      this.GetModelList(this.viewModel);
    },
    viweVideo(scope) {
      this.dialogVideoVisible = true
      this.playUrl = scope.row.PlayUrl0
    },
    pauseVideo() {
      this.$refs.playVideo.pause()
    },
    handleAdd() {
      this.addmodel = deepClone(defaultModel);
      this.addmodel.Items = []
      this.uploaderInfos = []
      this.$nextTick(() => {
        this.$refs["addmodel"].clearValidate(); //清空上次的错误验证提示
      });
      this.addVisible = true;
    },
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.model = deepClone(scope.row);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
        var fileIdElement = this.$refs.fileId
        var videourlElement = this.$refs.videourl
        var videoaddressElement = this.$refs.videoaddress
        fileIdElement.name = this.model.FileId
        videourlElement.name = this.model.DownloadUrl
        videoaddressElement.value = this.model.DownloadUrl

        console.log('fileIdElement.name', fileIdElement.name)
      });

    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }

      if (this.uploading) {
        this.$notify({
          title: "提示",
          type: "warning",
          message: "视频上传中，等待视频上传完成后再保存"
        });
        return false;
      }
      var fileIdElement = this.$refs.fileId
      var videourlElement = this.$refs.videourl

      if (fileIdElement.name) {

        this.model.FileId = fileIdElement.name
        this.model.DownloadUrl = videourlElement.name
      }

      var res = await PostModel(this.model);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.viewModel.page = 1;
      this.GetModelList(this.viewModel);
      this.model = deepClone(defaultModel);
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    handleDelete({ $index, row }) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await DeleteModel(row.Id);
          if (res && res.code == 200) {
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$notify({
              title: "失败",
              type: "error",
              message: res.message
            });
          }
          this.GetModelList(this.viewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },
    //图片上传成功回调
    handleAvatarSuccess(res, file) {
      //图片上传成功响应方法
      this.model.CoverUrl = res.data.SaveUrl
      this.model.ShowCoverUrl = res.data.DownloadUrl
      this.$notify({
        title: "成功",
        message: "上传完成!",
        type: "success",
        duration: 3000
      });
      this.loading = false
    },
    beforeAvatarUpload(file) {
      this.loading = true
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]

      const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传图片只能是 JPG/JPEG/PNG 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      return true
    },
    init() {
      this.tcVod = new TcVod({
        getSignature: getSignature
      })
    },
    //视频上传
    uploadvideo(file) {
      var mediaFile = file
      var that = this

      this.uploader = this.tcVod.upload({
        mediaFile: mediaFile, // 媒体文件（视频或音频或图片），类型为 File
      })

      this.uploader.on('media_progress', function (info) {
        console.log('info.percent', info.percent, "that--", that) // 进度
        var p = info.percent * 100
        that.progressStr = p.toFixed(0) + '%'
      })

      var fileIdElement = this.$refs.fileId
      var videourlElement = this.$refs.videourl

      this.uploader.done().then(function (doneResult) {
        // deal with doneResult
        console.log('doneResult', doneResult)
        fileIdElement.name = doneResult.fileId
        videourlElement.name = doneResult.video.url
        that.model.DownloadUrl = doneResult.video.url
        console.log('uploader.done()--fileIdElement.name', fileIdElement.name)
        that.uploading = false
        that.$refs.videoaddress.refresh()

      }).catch(function (err) {
        // deal with error
        console.log('uploader err', err)
      })
    },
    beforeUpload(file) {
      this.uploading = true
      this.progressStr = '0%'
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]

      const isImg = ext === 'mp4' || ext === 'MP4'

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传文件只能是 MP4 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }

      this.model.Size = parseInt(file.size / 1024)

      this.uploadvideo(file);

      return false
    },
    change(val) {
      var videourlElement = this.$refs.videourl
      var fileIdElement = this.$refs.fileId
      this.model.DownloadUrl = videourlElement.name
      this.model.FileId = fileIdElement.name
    }
  }
}